package cn.com.shuyangyang.common;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import javax.servlet.http.HttpServletRequest;

import cn.com.shuyangyang.common.util.GetAddrInfo;

/**
 * 请求参数处理
 * @author ShuYangYang
 * E-Mail:shuyangyang@aliyun.com
 * http://www.shuyangyang.com.cn
 * Date:2015年1月29日下午8:44:12
 *
 */
public class RequestContext implements Context{
	
	/** HTTP请求对象 */
	private HttpServletRequest request;

	/**当前请求参数对象 */
	private ConcurrentHashMap<String,String[]> parameters = new ConcurrentHashMap<String,String[]>();
	
	public RequestContext(HttpServletRequest request){
		this.setRequest(request);
		this.setParameters(request.getParameterMap());
		this.setValue("_sid", this.getValue("_sid") == null ? request.getSession().getId() : this.getValue("_sid"));
		this.setValue("_ip", GetAddrInfo.getIpAddr(request));
	}
	
	public HttpServletRequest getRequest() {
		return request;
	}

	public void setRequest(HttpServletRequest request) {
		this.request = request;
	}

	public ConcurrentHashMap<String, String[]> getParameters() {
		return parameters;
	}

	public void setParameters(Map<String, String[]> map) {
		this.parameters.putAll(map);
	}
	
	@Override
	public void setValue(String key, String value) {
		String[] tmp = new String[1];
		tmp[0] = value;
		this.parameters.put(key, tmp);
	}
	
	/**
	 * 参数表中是否包含指定的关键字
	 * @param key
	 * @return
	 */
	private boolean containsKey(String key) {
		return getParameters().containsKey(key);
	}

	@Override
	public String getValue(String key) {
		if(containsKey(key)) {
			return getParameters().get(key)[0].trim();
		} else {
			return null;
		}
	}
}
